#include "figurecontainer.h"
#include <fstream>

FigureContainer::FigureContainer()
{

}

FigureContainer::~FigureContainer()
{
    for(std::vector<Figure*>::iterator it = container.begin(); it != container.end(); ++it)
    {
        delete (*it);
    }
}

void FigureContainer::addFigure(Figure *fig)
{
    container.push_back(fig);
}

void FigureContainer::removeFigure(int i)
{
    delete container[i];
    container.erase(container.begin() + i);
}

Figure *FigureContainer::operator[](int i)
{
    return container[i];
}

void FigureContainer::writeFile(std::string fileName)
{
    std::ofstream file;
    file.open(fileName, std::ios::out);
    if(!file.is_open()) throw notWriteOpen;
    for(std::vector<Figure*>::iterator it = container.begin(); it != container.end(); ++it)
    {
        file << (*it)->dataToString();
        if (it != container.end() - 1) file << '\n';
    }
    file.close();
}

void FigureContainer::readFile(std::string fileName)
{
    std::ifstream file;
    file.open(fileName);
    if(!file.is_open()) throw notReadOpen;
    typeFigure type;
    std::string stringType;
    double doub;
    int n;
    std::vector<double> data;
    while (!file.eof())
    {
        file >> stringType;
        if(stringType == "Circle")
        {
            type = circle;
            n = 3;
        } else if (stringType == "Triangle")
        {
            type = triangle;
            n = 6;
        } else
        {
            type = rectangle;
            n = 4;
        }
        for (int i = 0; i < n; ++i)
        {
            file >> doub;
            data.push_back(doub);
        }
        addFigure(Figure::makeFigure(type, data));
        data.clear();
    }
    file.close();
}
